#include <fstream>

#include "debug.hpp"
#include "libpan.hpp"

using namespace std;

extern "C" void _declspec(dllexport) Callback(GunZPacket *packet)
{
	if(use)
	{
		char buf[SIZE_1K];

		memset(buf, 0, sizeof(buf));
		GetProgramDirectory(buf, sizeof(buf));
		_snprintf(buf, sizeof(buf), "%s\\debug.bin", buf);

		ofstream fout(buf, ios::out | ios::binary | ios::app);

		switch(packet->GetType())
		{
			case GUNZPACKET_DECRYPTED:					
				Print("Debug: Received a packet\n");
				Print("Debug: - Command ID: 0x%X\n", packet->GetCommandID());
				Print("Debug: - Packet size: %d byte(s)\n", packet->GetPacketSize());

				if(fout.is_open())
				{
					fout << "Debug: Received a packet\n";
					fout << "Debug: - Command ID: 0x" << uppercase << hex << packet->GetCommandID() << "\n";
					fout << "Debug: - Packet size: " << dec << packet->GetPacketSize() << " byte(s)\n";
					fout << "Debug: - Data:\n------------------------\n";
					fout.write(reinterpret_cast<char *>(packet->GetPacket()), packet->GetPacketSize());
					fout << "\n------------------------\n";
					fout.close();
				}
				else		
					Print("Debug: Could not read file: debug.bin\n");

				break;

			default:					
				Print("Debug: Received an unknown packet\n");

				if(fout.is_open())
				{
					fout << "Debug: Received an unknown packet\n";
					fout << "Debug: - Data:\n------------------------\n";
					fout.write(reinterpret_cast<char *>(packet->GetPacket()), SIZE_1K);
					fout << "\n------------------------\n";
					fout.close();
				}
				else	
					Print("Debug: Could not read file: debug.bin\n");

				break;
		}
	}
}

extern "C" void _declspec(dllexport) Init()
{
	char buf[SIZE_1K];

	memset(buf, 0, sizeof(buf));
	ExtractFromINI(GetINIContents(), "[Debug]", "Use = ", buf);

	if(!_stricmp(buf, "true"))
		use = true;

	else
		use = false;

	Print("Debug: Loaded config\n");
}